package com.jiaoxn.example.common.exception;

import com.jiaoxn.example.common.exception.custom.BusinessException;
import com.jiaoxn.example.common.exception.custom.ForbiddenException;
import com.jiaoxn.example.common.response.structure.ResponseStructure;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author jiao xn
 * @date 2022/8/28
 */
@RestControllerAdvice(basePackages = "com.jiaoxn.example")
public class ExceptionAdvice {
    /**
     * 捕获BusinessException异常
     */
    @ExceptionHandler({BusinessException.class})
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseStructure<?> handleBusinessException(BusinessException businessException) {
        return ResponseStructure.failed(businessException.getMessage());
    }

    /**
     * 捕获ForbiddenException异常
     */
    @ExceptionHandler({ForbiddenException.class})
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseStructure<?> handleForbiddenException(ForbiddenException forbiddenException) {
        return ResponseStructure.failed(forbiddenException.getMessage());
    }

    /**
     * 顶级异常捕获，当其他异常无法处理时选择使用
     */
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler({Exception.class})
    public ResponseStructure<?> handle(Exception exception) {
        return ResponseStructure.failed(exception.getMessage());
    }
}
